//
//  WZGLoginVC.m
//  ZCJZ
//
//  Created by sujeking on 2019/2/22.
//  Copyright © 2019年 jeking. All rights reserved.
//

#import "WZGLoginVC.h"
#import "ZCLoginViewModel.h"

#import "ZCRegsitVC.h"
#import "WZGResetPwdVC.h"
#import "RegisterJustNeed.h"
#import "WZGLoginPopVC.h"
#import "WZGAplyToShopkeeperVC.h"
#import "PaymentManager.h"
#import <BlocksKit+UIKit.h>
#import "SKBaseWebService.h"
#import <MJExtension.h>


@interface WZGLoginVC () <WXApiManagerDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *showPassBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (weak, nonatomic) IBOutlet UITextField *unameTF;
@property (weak, nonatomic) IBOutlet UITextField *upassTF;
@property (weak, nonatomic) IBOutlet UIButton *registBtn;
@property (weak, nonatomic) IBOutlet UIButton *wxbtn;

@property (weak, nonatomic) IBOutlet UIView *thirdview;
@property (assign, nonatomic) BOOL islogin;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titletopc;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *thirdviewheightc;


@end

@implementation WZGLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    {
        self.navigationController.navigationBar.translucent = YES;
        [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init]
                                                      forBarMetrics:UIBarMetricsDefault];
        //去掉透明后导航栏下边的黑边
        [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:UIColorFromRGB(0xffffff)};
        self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.unameTF becomeFirstResponder];
}

- (void)setupUI {
//    self.unameTF.text = @"侯建波";
//    self.upassTF.text = @"123456";
    //测试环境账号
//        self.unameTF.text = @"黄丽琴";
//        self.upassTF.text = @"840718";
//        self.unameTF.text = @"候一";
//    self.upassTF.text = @"12345678";
//    self.unameTF.text = @"昊天";
//    self.upassTF.text = @"123456";
    
    self.unameTF.delegate = self;
    
    UIImage *wximg = [UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e601", 30, UIColorFromRGB(0x333333))];
    [self.wxbtn setTitle:nil forState:UIControlStateNormal];
    [self.wxbtn setImage:wximg forState:UIControlStateNormal];
    self.wxbtn.backgroundColor = UIColorFromRGB(0xf5f5f5);
    self.wxbtn.layer.cornerRadius = CGRectGetHeight(self.wxbtn.bounds) / 2;
    self.wxbtn.layer.masksToBounds = YES;

    [self.wxbtn bk_addEventHandler:^(id sender) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        PaymentManager *manager = [PaymentManager sharedManager];
        manager.delegate = self;
        self.islogin = YES;
        [manager auth2WeiXinWithVC:self callback:^(NSString *msg) {
            
        }];
    } forControlEvents:UIControlEventTouchUpInside];
    
    self.upassTF.secureTextEntry = YES;
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIImage *closeimg = [UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e61e", 20, UIColorFromRGB(0x333333))];
    [self setLeftItemWithIcon:closeimg action:@selector(close4DismissViewController)];
    
    UIImage *showimg = [UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e646", 25, UIColorFromRGB(0x333333))];
    
    UIImage *hiddenimg = [UIImage iconWithInfo:TBCityIconInfoMake(@"\U0000e645", 25, UIColorFromRGB(0x333333))];
    
    [self.showPassBtn setTitle:nil forState:UIControlStateNormal];
    [self.showPassBtn setImage:showimg forState:UIControlStateSelected];
    [self.showPassBtn setImage:hiddenimg forState:UIControlStateNormal];
    
    self.loginBtn.layer.cornerRadius = CGRectGetHeight(self.loginBtn.bounds) / 2;
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.backgroundColor = [generalToolBox getColorWithHexadecimalColorStr:@"0xF9150F"];
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *uname = [ud valueForKey:@"unameTF"];
    if (uname != nil) {
        self.unameTF.text = uname;
    }
    
    if (![WXApi isWXAppInstalled]) {
        self.thirdview.hidden = YES;
    }
    
    self.titletopc.constant = 80 / 375.0 * [UIScreen mainScreen].bounds.size.width;
    self.thirdviewheightc.constant = 128 / 375.0 * [UIScreen mainScreen].bounds.size.width;
    
    ZCBaseUserManager *manager = [ZCBaseUserManager shareInstance];
    manager.userModel = nil;
}

- (void)close4DismissViewController {
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    __weak typeof(self) weakSelf = self;
    ZCBaseUserManager *manager = [ZCBaseUserManager shareInstance];
    manager.loginclosed = YES;
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        ZCBaseUserManager *manager = [ZCBaseUserManager shareInstance];
        manager.loginclosed = YES;
        manager.userModel = nil;
        if (weakSelf.goodsVCCallBack) {
            weakSelf.goodsVCCallBack(0);
        }
    }];
}

- (void)login4DismissViewController {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setValue:self.unameTF.text forKey:@"unameTF"];
    [ud setValue:self.upassTF.text forKey:@"upassTF"];
    [ud synchronize];
    
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccess" object:nil];
        [ZCLoginViewModel fetchShoppingCarNumWithComplete:^(ZCErrorCode status, NSString *message, id data) {
        }];
        if (weakSelf.goodsVCCallBack) {
            weakSelf.goodsVCCallBack(1);
        }
    }];
}

// MARK: - Action

- (IBAction)togleBtnAction:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    self.upassTF.secureTextEntry = !sender.selected;
}

- (IBAction)loginBtnClickAction:(id)sender {
    if (self.unameTF.text == nil || self.unameTF.text.length == 0) {
        [self.view makeToast:@"请输入账号" duration:2.0 position:CSToastPositionCenter];
        return;
    }
    if (self.upassTF.text == nil || self.upassTF.text.length == 0) {
        [self.view makeToast:@"请输入密码" duration:2.0 position:CSToastPositionCenter];
        return;
    }
    [self netLogin];
}

- (IBAction)registBtnClickAction:(id)sender {
    RegisterJustNeed *registerVC = [[RegisterJustNeed alloc] init];
    [self.navigationController pushViewController:registerVC animated:true];
}

- (IBAction)findPassBtnClickAction:(id)sender {
    WZGResetPwdVC *vc = [[WZGResetPwdVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)showPopVC {
    __weak typeof(self) weakSelf = self;
    WZGLoginPopVC *vc = [[WZGLoginPopVC alloc] init];
    [vc setBtnClickCallback:^(BOOL isAgree) {
        [weakSelf netPostProtocolStatus:isAgree];
    }];
    [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
    [self presentViewController:vc animated:YES completion:nil];
}

// MARK: - WXApiManagerDelegate

- (void)managerDidRecvAuthResponse:(SendAuthResp *)response {
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    switch (response.errCode) {
        case WXSuccess: {
            if (self.islogin) {
                NSString *code = response.code;
                [self netOtherPathLogin:code];
            } else {
                NSString *code = response.code;
                ZCRegsitVC *vc = [[ZCRegsitVC alloc] init];
                vc.wxcode = code;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
        case WXErrCodeUserCancel: {
            [self.view makeToast:@"授权取消" duration:2.0 position:CSToastPositionCenter];
        }
            break;
        case WXErrCodeSentFail:
        {
            [self.view makeToast:@"授权失败" duration:2.0 position:CSToastPositionCenter];
        }
            break;
        default:{
            
        }
            break;
    }
}

// MARK: - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@""]) {
        return YES;
    }
    if (textField.text.length >= 11) {
        return NO;
    }
    return YES;
}

// MARK: - NET

- (void)netLogin {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ZCLoginViewModel loginServerWithUserName:self.unameTF.text passWord:self.upassTF.text complete:^(ZCErrorCode status, NSString *message, id data) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        });
        if (status == kHXSNoError) {
            if (data == nil) {
                [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
            } else {
                [weakSelf netFetchAgreeProtolStatus];
            }
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

- (void)netOtherPathLogin:(NSString *)code {
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:code forKey:@"code"];
    __weak typeof(self) weakSelf = self;
    [SKBaseWebService postRequest:@"/v1/third/wxapp-login" parameters:parameters progress:nil success:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        ZCBaseUserManager *manager = [ZCBaseUserManager shareInstance];
        ZCBaseUserModel *userModel = [ZCBaseUserModel mj_objectWithKeyValues:data];
        manager.userModel = userModel;
        
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setValue:userModel.mj_keyValues forKey:@"userinfo"];
        [ud setValue:userModel.member.accessToken forKey:@"accessToken"];
        [ud synchronize];

        [weakSelf showPopVC];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"homereload" object:nil];
            [ZCLoginViewModel fetchShoppingCarNumWithComplete:^(ZCErrorCode status, NSString *message, id data) {
            }];
        });
    } failure:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        [weakSelf.view makeToast:msg duration:2.0 position:CSToastPositionCenter];
    }];
}

- (void)netFetchAgreeProtolStatus {
    ZCBaseUserManager *manager = [ZCBaseUserManager shareInstance];
    ZCBaseUserModel *userModel = manager.userModel;
    if (userModel.member.type == 1) {
        [self login4DismissViewController];
        return;
    }
    //店主以上弹出协议
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:@"index_page" forKey:@"position"];
    [SKBaseWebService postRequest:@"/v1/protocol/agree-status" parameters:parameters progress:nil success:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        BOOL kstatus = [[data valueForKey:@"status"] boolValue];
        if (kstatus) {
            [weakSelf login4DismissViewController];
        } else {
            [weakSelf showPopVC];
        }
    } failure:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        [weakSelf.view makeToast:msg duration:2.0 position:CSToastPositionCenter];
    }];
}

- (void)netPostProtocolStatus:(BOOL)status {
    if (!status) {
          NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
          
          [ud setValue:nil forKey:@"userinfo"];
          [ud setValue:nil forKey:@"upassTF"];
          [ud setValue:nil forKey:@"accessToken"];
          
          [ud removeObjectForKey:@"userinfo"];
          [ud removeObjectForKey:@"upassTF"];
          [ud removeObjectForKey:@"accessToken"];
          
          [ud synchronize];
      }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:@(status) forKey:@"status"];
    [parameters setValue:@"index_page" forKey:@"position"];
    __weak typeof(self) weakSelf = self;
    [SKBaseWebService postRequest:@"/v1/protocol/agree-protocol" parameters:parameters progress:nil success:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        [weakSelf login4DismissViewController];
    } failure:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        [weakSelf.view makeToast:msg duration:2.0 position:CSToastPositionCenter];
    }];
}


@end
